package com.example.a79273.shandianban.view;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.a79273.shandianban.R;
import com.example.a79273.shandianban.db.Login;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.List;

public class RegisterActivity extends AppCompatActivity {
    private EditText et_register_confirm, et_register_pass,
            et_register_vertify, et_register_number;


    private String name;
    private String pass;
    private String confirm;
    private DbManager dbManager;
    private DbManager.DaoConfig daoConfig;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initData();
        setData();
        setListener();
    }

    private void setListener() {
    }

    private void setData() {

    }

    private void initData() {
        daoConfig = new DbManager.DaoConfig();
        dbManager = x.getDb(daoConfig);

    }


    private void initView() {
        et_register_confirm = (EditText) findViewById(R.id.et_register_confirm);
        et_register_pass = (EditText) findViewById(R.id.et_register_pass);
        et_register_vertify = (EditText) findViewById(R.id.et_register_vertify);
        et_register_number = (EditText) findViewById(R.id.et_register_number);
    }

    public void onClick(View view) {
        name = et_register_number.getText().toString().trim();
        confirm = et_register_confirm.getText().toString().trim();
        pass = et_register_pass.getText().toString().trim();
        try {
            List<Login> username = dbManager.selector(Login.class).where
                    ("username", "=", name).findAll();//注册之前先查询是否有相同账号
            if (username != null &&username.size()>0) {//有同名用户
                Toast.makeText(RegisterActivity.this, "用户已存在", Toast
                        .LENGTH_SHORT).show();

            } else {//没有同名用户
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass) &&
                        confirm.equals(pass)) {
                    Login login = new Login();
                    login.setPassWord(pass);
                    login.setUserName(name);
                    dbManager.save(login);//存完了
                    List<Login> username1 = dbManager.selector(Login.class).where
                            ("username", "=", name).findAll();
                    if (username1 != null) {
                        Toast.makeText(RegisterActivity.this, "注册成功", Toast
                                .LENGTH_SHORT).show();
                    }
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

    }
}
